/*
 * ledset.cpp
 *
 *  Created on: 2021年12月10日
 *      Author: t1019
 */

#include "ledset.h"

namespace bt_led {

LedSet* LedSet::head = 0;

LedSet::LedSet(const s_SingleLed* led_info, bool type_invert)
{
	//把本对象链接到链表中
	if(head)
	{
		LedSet* p = head;
		while(p->next)
			p = p->next;
		p->next = this;
	}
	else
		head = this;
	next = 0;
	//配置LED信息
	led = led_info;
	invert = type_invert;
	status = SLED_OFF;
	nextstatus = SLED_OFF;
	change_timeout = 0;
	blink_timeout = 0;
}

void LedSet::set(e_LEDAction mode, uint16_t timeout, e_LEDAction nextmode)
{
	status = mode;
	blink_timeout = 0;
	change_timeout = timeout;
	nextstatus = nextmode;
}

void LedSet::_exec(uint16_t period)
{
	blink_timeout += period;
	switch(status)
	{
	case SLED_ON:
		_led_set(led,true);
		blink_timeout = 0;
		break;
	case SLED_FAST:
		if(blink_timeout<fast_t)
			_led_set(led,true);
		else
			_led_set(led,false);
		if(blink_timeout>=2*fast_t)
			blink_timeout = 0;
		break;
	case SLED_SLOW:
		if(blink_timeout<slow_t)
			_led_set(led,true);
		else
			_led_set(led,false);
		if(blink_timeout>=2*slow_t)
			blink_timeout = 0;
		break;
	case SLED_BLINK:
		if(blink_timeout<blink_on)
			_led_set(led,true);
		else
			_led_set(led,false);
		if(blink_timeout>=blink_off+blink_on)
			blink_timeout = 0;
		break;
	default:
	case SLED_OFF:
		_led_set(led,false);
		blink_timeout = 0;
		break;
	}
	if((status != SLED_OFF) && change_timeout>0)
	{
		if(change_timeout <= period)
		{
			change_timeout = 0;
			status = nextstatus;
		}
		else
			change_timeout -= period;
	}
}

void LedSet::handler(uint16_t period)
{
	LedSet* p = head;
	while(p)
	{
		p->_exec(period);
		p = p->next;
	}
}

LedSet::~LedSet()
{
	// TODO Auto-generated destructor stub
}

} /* namespace bt_led */
